package 面试;

//import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class ContainerNotSafeDemo {
    public static void main01(String[] args) {
        //ArrayList线程不安全，报ConcurrentModificationException
        //因为ArrayList的add方法不加synchronized
       // ArrayList<String> list = new ArrayList<>();

        //解决方案01：用Vector
        //List<String> list = new Vector<>();

        //解决方案02：用Collections.synchronizedList包围
        //List<String> list = Collections.synchronizedList(new ArrayList<>());

        //解决方案03：使用CopyOnWriteArrayList，写时复制技术
        List<String> list = new CopyOnWriteArrayList<>();

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                list.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(Thread.currentThread().getName()+": " +list);
            },String.valueOf(i)).start();
        }

    }

    public static void main02(String[] args){

        Set<String> set = new CopyOnWriteArraySet<>();
        //Collections.synchronizedSet(new HashSet<>());
        // new HashSet<>(); 线程不安全

        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                set.add(UUID.randomUUID().toString().substring(0,8));
                System.out.println(Thread.currentThread().getName()+": " +set);
            },String.valueOf(i)).start();
        }
    }

    public static void main(String[] args){

        Map<String,String> map = Collections.synchronizedMap(new HashMap<>());
        //new ConcurrentHashMap<>();
        // new HashMap<>(); 线程不安全


        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,8));
                System.out.println(Thread.currentThread().getName()+": " +map);
            },String.valueOf(i)).start();
        }
    }




}
